var http = require('http');
var s_url = require('url');
var Engine = require('velocity').Engine;
var querystring = require('querystring');
var fs = require("fs");
var util = require("./utils/util");

var self = null;
module.exports = {
	config: null,
	interface_callback: null,   //  接口回调
	server: null,
	/**
	 * 启动http服务
	 * @param config    配置
	 */
	start: function (config, interface_callback) {
		try{
			self = this;
			self.config = config;
			if (!self.config.enable) return;
			self.interface_callback = interface_callback;
			self.server = new http.Server();
			self.server.on('request',self.request);
			self.server.listen(self.config.port);
			console.log("http service start port:" + self.config.port);
		}catch (e){
			console.log("http service start error:" + e)
		}
	},
	request: function(request, response){
		try{
			var path = s_url.parse(request.url, true).pathname;
			if (path == "/favicon.ico") {
				if (self.config.ico) self.output_resources(request, response, self.config.ico);
				else response.end();
				return;
			}
			if(self.config.resources_regular.test(path)){
				self.output_resources(request, response, path);
				return;
			}else if (/([a-fA-F0-9]{32})/.test(path.substr(1))){
				console.log("md5");
			}else {
				let route = "";
				let action = "";
				if (path == "/" && self.config.init_url) path = self.config.init_url;
				
				let arr = path.substr(1).replace(/\//g, '.').split(/\./);
				if (arr.length == 1) {
					route = arr[0];
					action = self.config.default_action;
				}
				else {
					for (let i = 0; i < arr.length; i++){
						if (i != arr.length - 1) route += arr[i] + ".";
					}
					route = route.substr(0, route.length - 1);
					action = arr[arr.length - 1];
				}
				let params = self.get_request_params(request);
				self.interface_callback(route, action, params, (route_path, result) => {
					self.render(response, route_path, result);
				});
				return;
			}
		}catch (e){
			console.warn("http request error:" + e);
		}
		response.end();
	},
	get_request_params: function (request) {
		var params = null;
		if (request.method.toUpperCase() == 'POST') {
			throw "http service not accept POST request...";
			/*request.addListener("data", (data) => params += data);
			request.addListener("end", () => {
				params = querystring.parse(params);
			});*/
		}else if (request.method.toUpperCase() == 'GET') {
			params = s_url.parse(request.url, true).query;
		}
		return params;
	},
	output_resources: function (request, response, path) {
		util.fs.read_binary(self.config.resources_path + path, (data) => {
			if (data) {
				response.write(data, "binary");
				response.end();
			}else response.end();
		});
	},
	render: function (response, path, params) {
		if (!self.config.enable) return;
		util.fs.read(self.config.view_path + path, (data) => {
			if (data) {
				if (!params) params = {};
				response.writeHead(200, { 'Content-Type': 'text/html' });
				response.end(new Engine({template: data.toString()}).render(params));
			}else {
				response.writeHead(404, { 'Content-Type': 'text/html' });
				response.end("error");
			}
		});
	}
};